package com.xingkeduo.configuration.druid;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.xingkeduo.dao.operation"}, sqlSessionFactoryRef = "sqlSessionFactoryOperation")
public class OperationDruidDbConfig {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(OperationDruidDbConfig.class);
	
	@Autowired
    @Qualifier("operationDb")
    private DataSource operationDb;

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryOperation() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(operationDb);
        try {  
            //指定mapper xml目录  
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            factoryBean.setMapperLocations(resolver.getResources("classpath*:com/xingkeduo/dao/operation/mappers/*.xml"));
            return factoryBean.getObject();
        } catch (Exception e) {  
            logger.error(e.getMessage(), e);  
            throw new RuntimeException(e);  
        } 
    }

    @Bean("sqlSessionTemplateOperation")
    @Primary
    public SqlSessionTemplate sqlSessionTemplateOperation() throws Exception {
    	// 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryOperation());
        return template;
    }
}

